package com.anos.smsfun.activities;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Spannable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.anos.smsfun.R;
import com.anos.smsfun.adapter.IconListAdapter;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.customview.ChipsAdapter;
import com.anos.smsfun.customview.ChipsItem;
import com.anos.smsfun.customview.ChipsMultiAutoCompleteTextview;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.model.MessageItem;
import com.anos.smsfun.services.smsDeliveredReceiver;
import com.anos.smsfun.services.smsSentReceiver;
import com.anos.smsfun.task.QueryUtils;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.EmoticonsMgr;
import com.anos.smsfun.utility.Utils;

public class NewMessagingActivity extends Activity implements OnClickListener {

	private LinearLayout l_layout;
	private View l_right;
	private Button btnAddIcon;
	private Button btnSend;
	private Button btnAddContact;
	private EditText edInputText;
	private ScrollView scrollView;

	private TextView tvTitleBold;
	private TextView tvTitleSmall;

	private SMSFunDataCache mSmsFunDataCache;
	private ArrayList<ContactsWrapper> mListContacts = new ArrayList<ContactsWrapper>();
	private ArrayList<MessageItem> mMessageItems = new ArrayList<MessageItem>();
	private ArrayList<String> mListName = new ArrayList<String>();
	private ArrayList<String> mListPhone = new ArrayList<String>();
	private ArrayList<String> mListPhoneSendMSG = new ArrayList<String>();

	private BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

	private boolean mShowwingListIcon;
	private ArrayList<Integer> mArrIdIcons = new ArrayList<Integer>();
	private LinearLayout l_add_layout_icon;

	private ChipsAdapter mChipsAdapter;
	private ArrayList<ChipsItem> mChipsItems = new ArrayList<ChipsItem>();
	private ChipsMultiAutoCompleteTextview chipAutoComp;

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DefConstants.WHAT_SENT_RESULT_OK:
				break;

			case DefConstants.WHAT_SENT_RESULT_NO_SERVICE:
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_messaging);

		Utils.setUpActionBar(this);
		/**
		 * set title view
		 */
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflator.inflate(R.layout.title_view, null);
		tvTitleBold = (TextView) v.findViewById(R.id.tvTitle_ab);
		tvTitleSmall = (TextView) v.findViewById(R.id.tvNumber_ab);
		tvTitleBold.setText(getString(R.string.title_new_msg));
		tvTitleSmall.setText(getString(R.string.title_hint_new_msg));

		getActionBar().setCustomView(v);

		findViewByIdAll();

		// init
		mSmsFunDataCache = SMSFunDataCache.getInstance(this);

		// get bundle
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String strText = bundle
					.getString(DefConstants.ACTION_VIEW_FIND_CONTACT);
			edInputText.setText(strText);
		}

		// get list data
		getContactList();

	}

	private void findViewByIdAll() {
		l_add_layout_icon = (LinearLayout) findViewById(R.id.layout_add_layout_icon);
		edInputText = (EditText) findViewById(R.id.edInputMSG_choose);
		btnAddIcon = (Button) findViewById(R.id.btnInsertIcon_choose);
		btnAddContact = (Button) findViewById(R.id.btnAddContact_choose);
		btnSend = (Button) findViewById(R.id.btnSend_choose);
		l_layout = (LinearLayout) findViewById(R.id.layout_add_msg);
		scrollView = (ScrollView) findViewById(R.id.scroll_msg_send);

		chipAutoComp = (ChipsMultiAutoCompleteTextview) findViewById(R.id.chipsMultiAutoCompleteTextview1);

		btnAddContact.setOnClickListener(this);
		btnAddIcon.setOnClickListener(this);
		btnSend.setOnClickListener(this);
	}

	/**
	 * get list contact
	 */
	private void getContactList() {
		mListContacts = mSmsFunDataCache.getContactList();
		for (ContactsWrapper contact : mListContacts) {
			mListName.add(contact.getDisplayName());
			mListPhone.add(contact.getDisplayNumber());

			mChipsItems.add(new ChipsItem(contact.getDisplayName(), contact
					.getDisplayNumber(), R.drawable.ic_contact_picture_small));
		}

		mChipsAdapter = new ChipsAdapter(this, mChipsItems);
		chipAutoComp.setAdapter(mChipsAdapter);
	}

	@Override
	protected void onPause() {
		try {
			if (smsSentReceiver != null) {
				unregisterReceiver(smsSentReceiver);
			}
			if (smsDeliveredReceiver != null) {
				unregisterReceiver(smsDeliveredReceiver);
			}
		} catch (Exception ex) {
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		mMessageItems.clear();
		mMessageItems = null;
		mListContacts.clear();
		mListContacts = null;
		mListPhoneSendMSG.clear();
		mListPhoneSendMSG = null;
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			overridePendingTransition(0, R.anim.exit_slide_right);
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(0, R.anim.exit_slide_right);
		return;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAddContact_choose:
			Intent intent = new Intent(NewMessagingActivity.this,
					SelectContactActivity.class);
			startActivityForResult(intent, DefConstants.REQ_CODE_SELECT_CONTACT);
			overridePendingTransition(0, R.anim.exit_slide_left);
			break;
		case R.id.btnSend_choose:
			final String body = edInputText.getText().toString().trim();
			if (body.length() == 0)
				return;

			// add phone to list
			addPhoneToList();

			if (mListPhoneSendMSG.size() == 0) {
				Builder builder = new Builder(NewMessagingActivity.this);
				builder.setTitle(NewMessagingActivity.this
						.getString(R.string.app_name));
				builder.setMessage(NewMessagingActivity.this
						.getString(R.string.toast_input_contact_error));
				builder.setPositiveButton(
						NewMessagingActivity.this.getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
				return;
			}

			MessageItem msgItem = null;
			for (String phone : mListPhoneSendMSG) {
				msgItem = new MessageItem();
				msgItem.setAddress(phone);
				msgItem.setType(2);
				msgItem.setLongDate(System.currentTimeMillis());
				msgItem.setNameDisplay("");
				msgItem.setBody(body);
				msgItem.setStatus(1);

				// send msg
				if (sendSMS(msgItem)) {
					// insert
					QueryUtils.insertSmsSentItem(NewMessagingActivity.this,
							msgItem);
				}

				Log.e("Nummber", phone + "");
			}
			// refresh list
			edInputText.setText("");
			mMessageItems.add(0, msgItem);
			refreshDataList();

			break;

		case R.id.btnInsertIcon_choose:
			includeLayoutAddIcon();
			break;

		default:
			break;
		}
	}

	private void addPhoneToList() {
		mListPhoneSendMSG.clear();
		String text = chipAutoComp.getTextSelected();
		String[] arr = text.split(",");
		if (arr.length == 1 && arr[0].equals("")) {
			mListPhoneSendMSG.add(chipAutoComp.getText().toString());
			return;
		}

		for (String s : arr) {
			s = s.trim();
			int flag = 0;
			for (ChipsItem item : mChipsItems) {
				if (s.equals(item.getTitle())) {
					mListPhoneSendMSG.add(item.getNumber());
					flag = 1;
					break;
				}
			}
			if (flag == 0) {
				mListPhoneSendMSG.add(s);
			}
		}
	}

	private void refreshDataList() {
		if (mMessageItems == null || mMessageItems.isEmpty())
			return;

		// duyet list de add vao layout
		l_layout.removeAllViews();
		for (int i = mMessageItems.size() - 1; i >= 0; i--) {
			final MessageItem msgItem = mMessageItems.get(i);
			l_right = getLayoutInflater().inflate(
					R.layout.item_conversation_right, null);
			l_right.setId(msgItem.getId());
			final TextView tvBody = (TextView) l_right
					.findViewById(R.id.tvBody_conv_right);
			TextView tvTime = (TextView) l_right
					.findViewById(R.id.tvTime_conv_right);
			TextView tvStatus = (TextView) l_right
					.findViewById(R.id.tvIsSending_conv_right);
			tvTime.setText(msgItem
					.getFormatDate(DefConstants.DATE_FORMAT_DDMMHHMM));

			Spannable textBody = EmoticonsMgr.getSmiledText(
					NewMessagingActivity.this, msgItem.getBody());
			tvBody.setText(textBody);

			// status
			tvStatus.setVisibility(View.GONE);

			l_layout.addView(l_right);
		}

		// scroll xuống tin nhắn cuối cùng
		scrollView.post(new Runnable() {
			@Override
			public void run() {
				scrollView.fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (requestCode == DefConstants.REQ_CODE_SELECT_CONTACT) {
			Bundle bundle = data.getExtras();
			ArrayList<ContactsWrapper> contactSelecteds = bundle
					.getParcelableArrayList(DefConstants.PUT_LIST_SELECT_CONTACT);
			if (contactSelecteds.size() == 0)
				return;

			// updateListPhoneSelect(contactSelecteds);

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Hien thi danh sach contact dc chon len textbox
	 */
	// private void updateListPhoneSelect(
	// ArrayList<ContactsWrapper> contactSelecteds) {
	// mListPhoneSendMSG.clear();
	// String titleBold = "";
	// String titleSmall = "";
	// for (ContactsWrapper contact : contactSelecteds) {
	// mListPhoneSendMSG.add(contact.getDisplayNumber());
	// titleBold += contact.getDisplayName() + "; ";
	// titleSmall += contact.getDisplayNumber() + "; ";
	// addItemContact(contact.getDisplayNumber(), contact.getDisplayName());
	// }
	//
	// // update title
	// if (titleBold.length() > 30)
	// titleBold = titleBold.substring(0, 30) + "...";
	// if (titleSmall.length() > 30)
	// titleSmall = titleSmall.substring(0, 30) + "...";
	// tvTitleBold.setText(titleBold);
	// tvTitleSmall.setText(titleSmall);
	// }

	/**
	 * add item contact to textbox [Token edittext]
	 */
	// private void addItemContact(String phone, String name) {
	// final SpannableStringBuilder sb = new SpannableStringBuilder();
	// TextView tv = createContactTextView(phone, name);
	// BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(tv);
	// bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
	//
	// sb.append(name + " ");
	// sb.setSpan(new ImageSpan(bd), sb.length() - (name.length() + 1),
	// sb.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	// // mSearchAuto.append(sb);
	// // mSearchAuto.setSelection(mSearchAuto.getText().length());
	// }
	//
	// public TextView createContactTextView(String tag, String text) {
	// // creating textview dynamically
	// TextView tv = new TextView(this);
	// tv.setText(text);
	// tv.setTextSize(30);
	// tv.setBackgroundResource(R.drawable.bg_bubble_text);
	// tv.setCompoundDrawablesWithIntrinsicBounds(0, 0,
	// R.drawable.ic_search_close, 0);
	// return tv;
	// }
	//
	// @SuppressWarnings("deprecation")
	// public static Object convertViewToDrawable(View view) {
	// int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
	// view.measure(spec, spec);
	// view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
	// Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(),
	// view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
	// Canvas c = new Canvas(b);
	// c.translate(-view.getScrollX(), -view.getScrollY());
	// view.draw(c);
	// view.setDrawingCacheEnabled(true);
	// Bitmap cacheBmp = view.getDrawingCache();
	// Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
	// view.destroyDrawingCache();
	// return new BitmapDrawable(viewBmp);
	//
	// }

	/**
	 * *********************** ICON ***********************
	 */
	// load list icon
	private void includeLayoutAddIcon() {
		if (mShowwingListIcon) {
			l_add_layout_icon.removeAllViews();
			mShowwingListIcon = false;
			// show keyboard
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(edInputText, 0);
		} else {
			// hide keyboard
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(edInputText.getWindowToken(), 0);

			// include view
			View view = getLayoutInflater().inflate(
					R.layout.layout_display_icon, null);
			GridView gvIconList = (GridView) view.findViewById(R.id.gvListIcon);

			// numscolumn
			float scalefactor = getResources().getDisplayMetrics().density * 70;
			int number = getWindowManager().getDefaultDisplay().getWidth();
			int columns = (int) ((float) number / (float) scalefactor);
			gvIconList.setNumColumns(columns);

			// load all icon
			mArrIdIcons = EmoticonsMgr.getListIcons(this);

			IconListAdapter adapter = new IconListAdapter(this, mArrIdIcons);
			gvIconList.setAdapter(adapter);

			l_add_layout_icon.addView(view);
			mShowwingListIcon = true;

			gvIconList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapterView, View view,
						int i, long l) {
					final int idRes = mArrIdIcons.get(i);

					int cursorPosition = edInputText.getSelectionStart();
					String tempFirst = edInputText.getText().toString()
							.substring(0, cursorPosition);
					String tempLast = "";
					if (cursorPosition < edInputText.getText().length())
						tempLast = edInputText
								.getText()
								.toString()
								.substring(cursorPosition,
										edInputText.getText().length());

					tempFirst += EmoticonsMgr.getKeyByValue(idRes);
					tempFirst += tempLast;

					edInputText.setText(EmoticonsMgr.getSmiledText(
							NewMessagingActivity.this, tempFirst));
					edInputText.setSelection(edInputText.getText().length());
				}
			});
		}
	}

	// ////////////////////////////////////////////////////////////////
	// SEND SMS
	// ////////////////////////////////////////////////////////////////

	/**
	 * send sms to another device
	 */
	private boolean sendSMS(final MessageItem msgItem) {
		try {
			final int MAX_SMS_MESSAGE_LENGTH = 160;
			final String SENT = "SMS_SENT";
			final String DELIVERED = "SMS_DELIVERED";

			PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
					new Intent(SENT), 0);
			PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
					new Intent(DELIVERED), 0);

			smsSentReceiver = new smsSentReceiver(msgItem, mHandler);
			smsDeliveredReceiver = new smsDeliveredReceiver(msgItem);

			/**
			 * --when the SMS has been sent
			 */
			registerReceiver(smsSentReceiver, new IntentFilter(SENT));

			/**
			 * --when the SMS has been delivered
			 */
			registerReceiver(smsDeliveredReceiver, new IntentFilter(DELIVERED));

			SmsManager smsManager = SmsManager.getDefault();
			int length = msgItem.getBody().length();
			if (length > MAX_SMS_MESSAGE_LENGTH) {
				ArrayList<String> messagelist = smsManager
						.divideMessage(msgItem.getBody());
				smsManager.sendMultipartTextMessage(msgItem.getAddress(), null,
						messagelist, null, null);
			} else {
				smsManager.sendTextMessage(msgItem.getAddress(), null,
						msgItem.getBody(), sentPI, deliveredPI);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			// Toast.makeText(
			// NewMessagingActivity.this,
			// NewMessagingActivity.this
			// .getString(R.string.toast_input_contact_error),
			// Toast.LENGTH_SHORT).show();
			return false;
		}
	}

}
